const { wrongQuestionsAPI } = require('../../utils/api.js');

Page({
  data: {
    wrongQuestions: [
      {
        id: 1,
        number: 3,
        type: '计算题',
        content: '768 × 7 =',
        solution: '7/15 + 3/8 + 8/15 + 1/2',
        subject: '数学',
        grade: '四年级',
        difficulty: '中等',
        status: 'unmastered',
        hasVideo: true,
        date: '10/10 11:21'
      },
      {
        id: 2,
        number: 4,
        type: '解方程',
        content: '',
        solution: '',
        subject: '数学',
        grade: '四年级',
        difficulty: '中等',
        status: 'unmastered',
        hasVideo: true,
        date: '10/10 11:21'
      },
      {
        id: 3,
        number: 2,
        type: '口算题',
        content: '9 + 7 =\n1/3 + 3/4 =',
        solution: '3.5 + 1.6 + 2.7 =\n88 - 29 + 57 =',
        subject: '数学',
        grade: '四年级',
        difficulty: '简单',
        status: 'unmastered',
        hasVideo: true,
        date: '10/10 11:21'
      }
    ],
    subjects: [
      { id: 'all', name: '全部', color: '#666666', icon: 'all', count: 0 },
      { id: 'math', name: '数学', color: '#007aff', icon: 'calculator', count: 0 },
      { id: 'chinese', name: '语文', color: '#4ECDC4', icon: 'book', count: 0 },
      { id: 'english', name: '英语', color: '#45B7D1', icon: 'translate', count: 0 },
      { id: 'physics', name: '物理', color: '#85C1E9', icon: 'physics', count: 0 },
      { id: 'chemistry', name: '化学', color: '#F8C471', icon: 'chemistry', count: 0 },
      { id: 'biology', name: '生物', color: '#82E0AA', icon: 'biology', count: 0 }
    ],
    grades: ['全部', '一年级', '二年级', '三年级', '四年级', '五年级', '六年级'],
    difficulties: ['全部', '简单', '中等', '困难'],
    selectedSubject: 'all',
    selectedGrade: '全部',
    selectedDifficulty: '全部',
    searchKeyword: '',
    showFilter: false,
    showSearch: false,
    showSubjectManager: false,
    filteredQuestions: [],
    currentPage: 1,
    hasMore: true,
    isLoading: false,
    customSubjects: [],
    newSubjectName: '',
    newSubjectColor: '#FF6B6B',
    newSubjectIcon: 'book',
    searchFocused: false,
    showFilterControls: false,
    showFilterPanel: false,
    tempSelectedGrade: '',
    tempSelectedDifficulty: '',
    availableColors: [
      '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', 
      '#F8C471', '#82E0AA', '#F7DC6F', '#BB8FCE', 
      '#F1948A', '#AED6F1', '#D7BDE2', '#A9DFBF'
    ],
    availableIcons: [
      '/images/book.svg', '/images/calculator.svg', '/images/translate.svg', 
      '/images/science.svg', '/images/physics.svg', '/images/chemistry.svg',
      '/images/biology.svg', '/images/history.svg', '/images/geography.svg',
      '/images/politics.svg', '/images/music.svg', '/images/art.svg'
    ],
    selectedColor: '#FF6B6B',
    selectedIcon: '/images/book.svg'
  },

  onLoad: function (options) {
    console.log('错题页面加载');
    // 从本地存储获取用户信息（登录后存储）
    const userInfo = wx.getStorageSync('userInfo') || {};
    const userId = userInfo.userId || userInfo.id || userInfo.openid || null; // 兼容不同字段
    this.setData({ userId });
  
    // 默认科目名称（全部时传空）
    const subjectName = null;
    // 首次加载调用后端接口
    this.fetchWrongQuestions(userId, subjectName);
  },

  onShow: function () {
    console.log('错题页面显示');
  },

  onPullDownRefresh: function () {
    console.log('下拉刷新');
    setTimeout(() => {
      wx.stopPullDownRefresh();
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    }, 1000);
  },

  onReachBottom: function () {
    console.log('上拉加载更多');
    if (!this.data.hasMore || this.data.isLoading) {
      this.setData({ hasMore: false, isLoading: false });
      return;
    }
    this.setData({ isLoading: true });
    setTimeout(() => {
      this.setData({ isLoading: false, hasMore: false });
    }, 800);
  },

  updateSubjectCounts: function() {
    const allSubjects = [...this.data.subjects, ...this.data.customSubjects];
    allSubjects.forEach(subject => {
      if (subject.name === '全部') {
        subject.count = this.data.wrongQuestions.length;
      } else {
        subject.count = this.data.wrongQuestions.filter(q => q.subject === subject.name).length;
      }
    });
    
    const updatedSubjects = this.data.subjects.map(subject => {
      const found = allSubjects.find(s => s.name === subject.name);
      return found ? { ...subject, count: found.count } : subject;
    });
    
    const updatedCustomSubjects = this.data.customSubjects.map(subject => {
      const found = allSubjects.find(s => s.name === subject.name);
      return found ? { ...subject, count: found.count } : subject;
    });
    
    this.setData({
      subjects: updatedSubjects,
      customSubjects: updatedCustomSubjects
    });
  },

  toggleSearch: function() {
    this.setData({
      showSearch: !this.data.showSearch,
      searchKeyword: this.data.showSearch ? '' : this.data.searchKeyword
    });
    if (!this.data.showSearch) {
      this.filterQuestions();
    }
  },

  onSearchInput: function(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
    this.filterQuestions();
  },

  onSearchFocus: function() {
    this.setData({
      searchFocused: true
    });
  },

  onSearchBlur: function() {
    this.setData({
      searchFocused: false
    });
  },

  clearSearch: function() {
    this.setData({
      searchKeyword: ''
    });
    this.filterQuestions();
  },

  toggleFilter: function() {
    this.setData({
      showFilterPanel: !this.data.showFilterPanel,
      showFilterControls: !this.data.showFilterControls,
      tempSelectedGrade: this.data.selectedGrade,
      tempSelectedDifficulty: this.data.selectedDifficulty
    });
  },

  closeFilter: function() {
    this.setData({
      showFilterPanel: false,
      showFilterControls: false
    });
  },

  resetFilter: function() {
    this.setData({
      tempSelectedGrade: '全部',
      tempSelectedDifficulty: '全部'
    });
  },

  confirmFilter: function() {
    this.setData({
      selectedGrade: this.data.tempSelectedGrade,
      selectedDifficulty: this.data.tempSelectedDifficulty,
      showFilterPanel: false,
      showFilterControls: false
    });
    this.filterQuestions();
  },

  // 根据用户ID与科目名称查询后端数据并更新页面
  fetchWrongQuestions: function(userId, subjectName) {
    if (!userId) {
      wx.showToast({ title: '未获取到用户信息，请先登录', icon: 'none' });
      return;
    }
    wx.showLoading({ title: '加载中...', mask: true });
    wrongQuestionsAPI.queryByUserIdAndSubject(userId, subjectName)
      .then(list => {
        // 对后端返回进行归一化，兼容不同字段命名
        const normalized = (Array.isArray(list) ? list : []).map(item => ({
          id: item.id || item.questionId || item.qid,
          number: item.number || item.num || item.index,
          type: item.type || item.questionType || '',
          content: item.content || item.questionContent || item.title || '',
          solution: item.solution || item.answer || '',
          subject: item.subject || item.subjectName || item.subject_name || '',
          grade: item.grade || item.gradeName || item.grade_name || '全部',
          difficulty: item.difficulty || item.level || item.difficulty_level || '中等',
          status: item.status || (item.mastered ? 'mastered' : 'unmastered'),
          hasVideo: typeof item.hasVideo === 'boolean' ? item.hasVideo : !!(item.videoUrl || item.video_url),
          date: item.date || item.createTime || item.create_time || ''
        }));
        this.setData({ wrongQuestions: normalized });
        this.updateSubjectCounts();
        this.filterQuestions();
      })
      .catch(err => {
        console.error('查询错题失败:', err);
        wx.showToast({ title: err.message || '查询失败', icon: 'none' });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  onSubjectTap: function (e) {
    const subject = e.currentTarget.dataset.subject;
    this.setData({ selectedSubject: subject });
    // 将科目ID转换为名称，all 传空
    const subjectName = subject === 'all' ? null : (this.data.subjects.find(s => s.id === subject)?.name || null);
    const userId = this.data.userId || (wx.getStorageSync('userInfo') || {}).userId || (wx.getStorageSync('userInfo') || {}).id || (wx.getStorageSync('userInfo') || {}).openid || null;
    // 触发后端查询
    this.fetchWrongQuestions(userId, subjectName);
  },

  onGradeTap: function (e) {
    const grade = e.currentTarget.dataset.grade;
    this.setData({
      tempSelectedGrade: grade
    });
  },

  onDifficultyTap: function (e) {
    const difficulty = e.currentTarget.dataset.difficulty;
    this.setData({
      tempSelectedDifficulty: difficulty
    });
  },

  filterQuestions: function() {
    let filtered = this.data.wrongQuestions;
    
    if (this.data.selectedSubject !== 'all') {
      const selectedSubjectName = this.data.subjects.find(s => s.id === this.data.selectedSubject)?.name;
      if (selectedSubjectName) {
        filtered = filtered.filter(q => q.subject === selectedSubjectName);
      }
    }
    
    if (this.data.selectedGrade !== '全部') {
      filtered = filtered.filter(q => q.grade === this.data.selectedGrade);
    }
    
    if (this.data.selectedDifficulty !== '全部') {
      filtered = filtered.filter(q => q.difficulty === this.data.selectedDifficulty);
    }
    
    if (this.data.searchKeyword) {
      const keyword = this.data.searchKeyword.toLowerCase();
      filtered = filtered.filter(q => 
        q.content.toLowerCase().includes(keyword) ||
        (q.type && q.type.toLowerCase().includes(keyword))
      );
    }
    
    this.setData({
      filteredQuestions: filtered,
      // 静态数据下默认没有更多，显示“已经到底啦”
      isLoading: false,
      hasMore: false
    });
  },

  onQuestionTap: function (e) {
    const questionId = e.currentTarget.dataset.id;
    if (!questionId) {
      wx.showToast({ title: '未获取到题目ID', icon: 'none' });
      return;
    }
    wx.navigateTo({
      url: `/pages/wrong-detail/wrong-detail?id=${questionId}`
    });
  },

  onDeleteQuestion: function (e) {
    const questionId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这道错题吗？',
      success: (res) => {
        if (res.confirm) {
          const wrongQuestions = this.data.wrongQuestions.filter(item => item.id !== questionId);
          this.setData({
            wrongQuestions: wrongQuestions
          });
          this.updateSubjectCounts();
          this.filterQuestions();
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  onCollectQuestion: function (e) {
    const questionId = e.currentTarget.dataset.id;
    console.log('收藏题目:', questionId);
    wx.showToast({
      title: '收藏成功',
      icon: 'success'
    });
  },

  onPracticeAgain: function (e) {
    const questionId = e.currentTarget.dataset.id;
    console.log('重新练习题目:', questionId);
    wx.showToast({
      title: '重新练习功能开发中',
      icon: 'none'
    });
  },

  onBatchPractice: function() {
    if (this.data.filteredQuestions.length === 0) {
      wx.showToast({
        title: '没有可练习的题目',
        icon: 'none'
      });
      return;
    }
    
    console.log('批量练习题目');
    wx.showToast({
      title: '批量练习功能开发中',
      icon: 'none'
    });
  },

  onBatchDelete: function() {
    if (this.data.filteredQuestions.length === 0) {
      wx.showToast({
        title: '没有可删除的题目',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '确认删除',
      content: `确定要删除当前筛选的 ${this.data.filteredQuestions.length} 道错题吗？`,
      success: (res) => {
        if (res.confirm) {
          const filteredIds = this.data.filteredQuestions.map(q => q.id);
          const wrongQuestions = this.data.wrongQuestions.filter(item => !filteredIds.includes(item.id));
          this.setData({
            wrongQuestions: wrongQuestions
          });
          this.updateSubjectCounts();
          this.filterQuestions();
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  onUploadQuestion: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera', 'album'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        });
      },
      fail: () => {
        wx.showToast({
          title: '上传失败',
          icon: 'error'
        });
      }
    });
  },

  showSubjectManager: function() {
    this.setData({
      showSubjectManager: true
    });
  },

  hideSubjectManager: function() {
    this.setData({
      showSubjectManager: false,
      newSubjectName: '',
      newSubjectColor: '#FF6B6B',
      newSubjectIcon: 'book'
    });
  },

  onNewSubjectNameInput: function(e) {
    this.setData({
      newSubjectName: e.detail.value
    });
  },

  onColorSelect: function(e) {
    const color = e.currentTarget.dataset.color;
    this.setData({
      selectedColor: color,
      newSubjectColor: color
    });
  },

  onIconSelect: function(e) {
    const icon = e.currentTarget.dataset.icon;
    this.setData({
      selectedIcon: icon,
      newSubjectIcon: icon
    });
  },

  addNewSubject: function() {
    const { newSubjectName, newSubjectColor, newSubjectIcon, subjects, customSubjects } = this.data;
    
    if (!newSubjectName.trim()) {
      wx.showToast({
        title: '请输入科目名称',
        icon: 'none'
      });
      return;
    }

    const allSubjects = [...subjects, ...customSubjects];
    if (allSubjects.some(subject => subject.name === newSubjectName.trim())) {
      wx.showToast({
        title: '科目已存在',
        icon: 'none'
      });
      return;
    }

    const newSubject = {
      name: newSubjectName.trim(),
      color: newSubjectColor,
      icon: newSubjectIcon,
      count: 0,
      isCustom: true
    };

    this.setData({
      customSubjects: [...customSubjects, newSubject],
      newSubjectName: '',
      newSubjectColor: '#FF6B6B',
      newSubjectIcon: 'book',
      selectedColor: '#FF6B6B',
      selectedIcon: '/images/book.svg'
    });

    wx.showToast({
      title: '添加成功',
      icon: 'success'
    });
  },

  deleteCustomSubject: function(e) {
    const index = e.currentTarget.dataset.index;
    const customSubjects = this.data.customSubjects;
    const subjectName = customSubjects[index].name;

    wx.showModal({
      title: '确认删除',
      content: `确定要删除科目"${subjectName}"吗？`,
      success: (res) => {
        if (res.confirm) {
          customSubjects.splice(index, 1);
          this.setData({
            customSubjects: customSubjects
          });
          
          if (this.data.selectedSubject === subjectName) {
            this.setData({
              selectedSubject: '全部'
            });
            this.filterQuestions();
          }

          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  getAllSubjects: function() {
    return [...this.data.subjects, ...this.data.customSubjects];
  }
});